package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FocusUserApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.soap.SOAPBinding;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SmallVideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FocusUserApi focusUserApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    @CacheEvict(value = "videoList", allEntries = true)
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        String filename = videoFile.getOriginalFilename();
        String suffixName = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), suffixName, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());

        Video video = new Video();
        video.setCreated(System.currentTimeMillis());
        video.setUserId(UserHolder.getId());
        video.setText("想你的夜");
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        video.setLikeCount(0);
        video.setCommentCount(0);
        video.setLoveCount(0);
        video.setId(ObjectId.get());

        videoApi.saveVideo(video);
        mqMessageService.sendLogService(UserHolder.getId(), "0301", "video", video.getId().toString());
    }

    @Cacheable(value = "videoList", key = "#page + '_' +  #pagesize")
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        PageResult pageResult = videoApi.queryVideoList(page, pagesize);
        List<Video> videoList = (List<Video>) pageResult.getItems();
        List<Long> userIds = CollUtil.getFieldValues(videoList, "userId", Long.class);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds);
        List<VideoVo> voList = new ArrayList<>();
        for (Video video : videoList) {
            UserInfo userInfo = userInfoMap.get(video.getUserId());
            VideoVo vo = VideoVo.init(userInfo, video);

            String key1 = Constants.FOCUS_USER_KEY + UserHolder.getId();
            String hashkey1 = String.valueOf(video.getUserId());
            if (redisTemplate.opsForHash().hasKey(key1, hashkey1)) {
                vo.setHasFocus(1);
            }

            String key2 = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getId();
            String hashkey2 = String.valueOf(video.getId());
            if(redisTemplate.opsForHash().hasKey(key2,hashkey2)){
                vo.setHasLiked(1);
            }
            voList.add(vo);
        }
        pageResult.setItems(voList);
        return pageResult;
    }

    public void focusUser(Long followUserId) {
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(UserHolder.getId());
        focusUser.setFollowUserId(followUserId);
        focusUser.setCreated(System.currentTimeMillis());
        focusUserApi.saveFocus(focusUser);

        String key = Constants.FOCUS_USER_KEY + UserHolder.getId();
        String hashkey = String.valueOf(followUserId);
        redisTemplate.opsForHash().put(key, hashkey, "1");

    }

    public void unfocusUser(Long followUserId) {
        Long userId = UserHolder.getId();
        focusUserApi.unFocus(userId, followUserId);

        //取消关注标记
        String key = Constants.FOCUS_USER_KEY + userId;
        String hashkey = String.valueOf(followUserId);
        redisTemplate.opsForHash().delete(key, hashkey);
    }


}